import dataclasses
import typing as t

import rio

from .component import AccessibilityRole, Component, Key

__all__ = ["TabItem", "Tabs"]


@dataclasses.dataclass(frozen=True)
class TabItem:
    title: str
    content: Component
    icon: str | None = None


class Tabs(Component):
    tabs: t.Sequence[TabItem]
    active_tab_index: int = 0

    def __init__(
        self,
        *tabs: TabItem,
        active_tab_index: int = 0,
        key: Key | None = None,
        margin: float | None = None,
        margin_x: float | None = None,
        margin_y: float | None = None,
        margin_left: float | None = None,
        margin_top: float | None = None,
        margin_right: float | None = None,
        margin_bottom: float | None = None,
        min_width: float = 0,
        min_height: float = 0,
        # MAX-SIZE-BRANCH max_width: float | None = None,
        # MAX-SIZE-BRANCH max_height: float | None = None,
        grow_x: bool = False,
        grow_y: bool = False,
        align_x: float | None = None,
        align_y: float | None = None,
        # SCROLLING-REWORK scroll_x: t.Literal["never", "auto", "always"] = "never",
        # SCROLLING-REWORK scroll_y: t.Literal["never", "auto", "always"] = "never",
        accessibility_role: AccessibilityRole | None = None,
    ):
        super().__init__(
            key=key,
            margin=margin,
            margin_x=margin_x,
            margin_y=margin_y,
            margin_left=margin_left,
            margin_top=margin_top,
            margin_right=margin_right,
            margin_bottom=margin_bottom,
            min_width=min_width,
            min_height=min_height,
            # MAX-SIZE-BRANCH max_width=max_width,
            # MAX-SIZE-BRANCH max_height=max_height,
            grow_x=grow_x,
            grow_y=grow_y,
            align_x=align_x,
            align_y=align_y,
            # SCROLLING-REWORK scroll_x=scroll_x,
            # SCROLLING-REWORK scroll_y=scroll_y,
            accessibility_role=accessibility_role,
        )

        self.tabs = tabs
        self.active_tab_index = active_tab_index

    def build(self) -> Component:
        try:
            content = self.tabs[self.active_tab_index].content
        except IndexError:
            content = None

        return rio.Column(
            rio.SwitcherBar(
                *[
                    rio.SwitcherBarItem(index, tab.title, tab.icon)
                    for index, tab in enumerate(self.tabs)
                ],
                selected_value=self.bind().active_tab_index,
                align_x=0,
            ),
            rio.Switcher(content, grow_y=True),
        )
